package com.toune.wxtool

import android.app.Application
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.provider.SyncStateContract
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory


object WxTool {
    private lateinit var cxt: Application
    fun init(cxt: Application, appKey: String, appSecret: String?) {
        this.cxt = cxt
        context = cxt.applicationContext
        APP_ID = appKey
        regToWx()
    }

    // APP_ID 替换为你的应用从官方网站申请到的合法appID
    private var APP_ID = "wx88888888"

    // IWXAPI 是第三方app和微信通信的openApi接口
    var api: IWXAPI? = null

    private fun regToWx() {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(cxt, APP_ID, true)

        // 将应用的appId注册到微信
        api!!.registerApp(APP_ID)

        //建议动态监听微信启动广播进行注册到微信
        cxt.registerReceiver(object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {

                // 将该app注册到微信
                api!!.registerApp(APP_ID)
            }
        }, IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP))
    }

    var reqState = "hello_toune"
    /**
     * 微信登录
     */
    fun loginWx() {
        // send oauth request
        if (api == null) {
            throw NullPointerException("请先调用init()方法")
        } else {
            var req = SendAuth.Req()
            req.scope = "snsapi_userinfo"
            req.state = reqState
            api!!.sendReq(req)
        }
    }

    var context: Context? = null
        get() {
            if (field == null) {
                throw NullPointerException("请先调用init()方法")
            }
            return field
        }
        set(value) {
            field = value
        }
}